package com.fintech.pangu.autoconfigure.security.authorize;

import com.fintech.pangu.autoconfigure.security.properties.PanGuSecurityProperties;
import com.fintech.pangu.security.authorize.AuthorizeCacheSynchronizer;
import com.fintech.pangu.security.authorize.AuthorizeConfigProvider;
import com.fintech.pangu.security.authorize.RbacAuthorizeConfigProvider;
import com.fintech.pangu.security.authorize.RestRbacAuthorizeCacheSynchronizer;
import com.fintech.pangu.security.authorize.impl.AuthorizeCacheSynchronizerInitializer;
import com.fintech.pangu.security.authorize.service.RbacAuthorizeService;
import com.fintech.pangu.security.authorize.service.impl.RbacAuthorizeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RBAC授权自动配置
 */
@Configuration
@EnableConfigurationProperties(PanGuSecurityProperties.class)
@ConditionalOnClass(RbacAuthorizeConfigProvider.class)
public class SecurityAuthorizeRBACAutoConfiguration {

    @Autowired
    public PanGuSecurityProperties panGuSecurityProperties;

    /**
     * RBAC权限校验服务
     * @return
     */
    @Bean
    public RbacAuthorizeService rbacAuthorizeService(){
        return new RbacAuthorizeServiceImpl();
    }

    /**
     * RBAC权限配置提供者
     * @return
     */
    @Bean
    public AuthorizeConfigProvider rbacAuthorizeConfigProvider(){
        return new RbacAuthorizeConfigProvider();
    }


    /**
     * 基于Rest请求的Rbac权限缓存同步器
     * @return
     */
    @Bean
    public AuthorizeCacheSynchronizer restRbacAuthorizeCacheSynchronizer(){
        RestRbacAuthorizeCacheSynchronizer restRbacAuthorizeCacheSynchronizer = new RestRbacAuthorizeCacheSynchronizer();
        return restRbacAuthorizeCacheSynchronizer;
    }

    /**
     * 权限缓存初始化器，会启动同步器
     * @return
     */
    @Bean
    public AuthorizeCacheSynchronizerInitializer rbacAuthorizeCacheInitializer(){
        // 构造初始化器，传入同步器及其initialDelayMs、intervalMs
        AuthorizeCacheSynchronizerInitializer rbacAuthorizeCacheInitializer =
                new AuthorizeCacheSynchronizerInitializer(
                        restRbacAuthorizeCacheSynchronizer(),
                        panGuSecurityProperties.getAuthorize().getCacheSync().getInitialDelayMs(),
                        panGuSecurityProperties.getAuthorize().getCacheSync().getIntervalMs()
                );
        return rbacAuthorizeCacheInitializer;
    }

}
